<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      title="添加实体视图"
      ok-text="保存"
      :closeFunc="close"
      :destroy-on-close="true"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm">
        <template #entityViewType="{ field, model }">
          <AutoComplete
            v-model:value="model[field]"
            :options="options"
            placeholder="请输入实体视图类型"
            :filter-option="filterOption"
          />
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemas } from './addEntityModal.data';
  import { AutoComplete } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import dayjs from 'dayjs';
  import {
    getViewInfo,
    getEntityViewTypeList,
    getDeviceInfo,
    getAssetInfo,
    getAttributeKeys,
    getTimeseries,
    getEntityDeviceList,
    getEntityAssetList,
  } from '/@/api/thingsborad/entity/entity';
  import { entityViewType, BasicOptions } from '/@/api/thingsborad/entity/model/entityModel';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useDebounceFn } from '@vueuse/core';
  const emit = defineEmits(['success']);
  const mode = ref('');
  const options = ref<Array<BasicOptions>>([]);
  let viewValues: any;
  const entityName = ref('');
  const [registerForm, { validate, setFieldsValue, resetFields, updateSchema, getFieldsValue }] =
    useForm({
      layout: 'vertical',
      schemas,
      showActionButtonGroup: false,
      ...modalFormStyleSetting,
    });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    mode.value = data.key;
    if (data?.key == 'edit') {
      setModalProps({
        title: '编辑',
        loading: true,
        ...modalStyleSetting,
      });
      viewValues = await getViewInfo(data.record.id);
      let entityInfo: any;
      if (viewValues.entityId.entityType == 'DEVICE') {
        entityInfo = await getDeviceInfo(viewValues.entityId.id);
      } else {
        entityInfo = await getAssetInfo(viewValues.entityId.id);
      }
      entityName.value = entityInfo.name;
      viewValues.startTimeMs == null ? (viewValues.startTimeMs = 0) : viewValues.startTimeMs;
      viewValues.endTimeMs == null ? (viewValues.endTimeMs = 0) : viewValues.endTimeMs;
      // updateSchema({
      //   field: 'type',
      //   defaultValue: viewValues.entityId.entityType,
      // });
      setFieldsValue({
        entityName: viewValues.name,
        entityViewType: viewValues.type,
        type: viewValues.entityId.entityType,
        device: viewValues.entityId.id,
        asset: viewValues.entityId.id,
        clientProperties:
          viewValues.keys.attributes.cs == null ? undefined : viewValues.keys.attributes.cs,
        sharedProperty:
          viewValues.keys.attributes.sh == null ? undefined : viewValues.keys.attributes.sh,
        serverProperties:
          viewValues.keys.attributes.ss == null ? undefined : viewValues.keys.attributes.ss,
        timeSeries: viewValues.keys.timeseries == null ? undefined : viewValues.keys.timeseries,
        dateRange:
          viewValues.startTimeMs == 0 && viewValues.endTimeMs == 0
            ? undefined
            : [dayjs(viewValues.startTimeMs), dayjs(viewValues.endTimeMs)],
        remark: viewValues.additionalInfo.description,
      });
      initSchema();
      setModalProps({
        loading: false,
      });
    } else {
      initSchema();
      setModalProps({
        title: '添加实体视图',
        ...modalStyleSetting,
      });
    }
  });

  async function close() {
    resetFields();
    return true;
  }

  async function handleSubmit() {
    if (mode.value == 'add') {
      try {
        const values = await validate();
        emit('success', { key: 'add', values });
        closeModal();
        resetFields();
        init();
      } catch (error) {}
    } else if (mode.value == 'edit') {
      try {
        const values = await validate();
        emit('success', { key: 'edit', values, viewValues });
        closeModal();
        resetFields();
        init();
      } catch (error) {}
    }
  }

  function filterOption(input: string, option: any) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  onMounted(() => {
    init();
  });
  async function init() {
    options.value = [];
    const values: entityViewType[] = await getEntityViewTypeList();
    values.forEach((item) => {
      options.value.push({
        label: item.type,
        value: item.type,
      });
    });
  }
  // 初始化表单数据
  function initSchema() {
    updateSchema([
      {
        field: 'clientProperties',
        componentProps: () => {
          const { type, device, asset } = getFieldsValue();
          const params = {
            entityType: type,
            entityId: type == 'DEVICE' ? device : asset,
          };
          return {
            placeholder: '请选择客户端属性',
            mode: 'multiple',
            maxTagCount: 'responsive',
            listHeight: 160,
            api: getAttributeKeys,
            params,
            immediate: false,
            alwaysLoad: true,
            strArrToObjArr: true,
          };
        },
      },
      {
        field: 'sharedProperty',
        componentProps: () => {
          const { type, device, asset } = getFieldsValue();
          const params = {
            entityType: type,
            entityId: type == 'DEVICE' ? device : asset,
          };
          return {
            placeholder: '请选择共享属性',
            mode: 'multiple',
            maxTagCount: 'responsive',
            listHeight: 160,
            api: getAttributeKeys,
            params,
            immediate: false,
            alwaysLoad: true,
            strArrToObjArr: true,
          };
        },
      },
      {
        field: 'serverProperties',
        componentProps: () => {
          const { type, device, asset } = getFieldsValue();
          const params = {
            entityType: type,
            entityId: type == 'DEVICE' ? device : asset,
          };
          return {
            placeholder: '请选择服务端属性',
            mode: 'multiple',
            maxTagCount: 'responsive',
            listHeight: 160,
            api: getAttributeKeys,
            params,
            immediate: false,
            alwaysLoad: true,
            strArrToObjArr: true,
          };
        },
      },
      {
        field: 'timeSeries',
        componentProps: () => {
          const { type, device, asset } = getFieldsValue();
          const params = {
            entityType: type,
            entityId: type == 'DEVICE' ? device : asset,
          };
          return {
            placeholder: '请选择时间序列',
            mode: 'multiple',
            maxTagCount: 'responsive',
            listHeight: 160,
            api: getTimeseries,
            params,
            immediate: false,
            alwaysLoad: true,
            strArrToObjArr: true,
          };
        },
      },
      {
        field: 'type',
        componentProps: () => {
          return {
            allowClear: false,
            placeholder: '请输入类型',
            options: [
              {
                label: '设备',
                value: 'DEVICE',
              },
              {
                label: '资产',
                value: 'ASSET',
              },
            ],
            onChange: (value) => {
              entityName.value = '';
              switch (value) {
                case 'DEVICE':
                  setFieldsValue({ device: null });
                  break;
                case 'ASSET':
                  setFieldsValue({ asset: null });
                  break;
              }
            },
          };
        },
      },
      {
        field: 'device',
        componentProps: ({ formActionType }) => {
          const params = ref({
            page: 0,
            pageSize: 10,
            sortProperty: 'name',
            sortOrder: 'ASC',
            textSearch: entityName.value,
          });
          return {
            listHeight: 160,
            options: [{ label: '1', value: '1' }],
            api: getEntityDeviceList,
            placeholder: '请选择设备',
            showSearch: true,
            params: params.value,
            resultField: 'data',
            labelField: 'name',
            valueField: 'id.id',
            immediate: true,
            onSearch: useDebounceFn((e) => {
              entityName.value = e;
            }, 300),
            onChange: () => {
              try {
                const { updateSchema } = formActionType;
                updateSchema([
                  {
                    field: 'clientProperties',
                    show: true,
                  },
                  {
                    field: 'sharedProperty',
                    show: true,
                  },
                  {
                    field: 'serverProperties',
                    show: true,
                  },
                  {
                    field: 'timeSeries',
                    show: true,
                  },
                ]);
              } catch (error) {}
            },
          };
        },
      },
      {
        field: 'asset',
        componentProps: ({ formActionType }) => {
          const params = ref({
            page: 0,
            pageSize: 10,
            sortProperty: 'name',
            sortOrder: 'ASC',
            textSearch: entityName.value,
          });
          return {
            listHeight: 160,
            showSearch: true,
            options: [],
            api: getEntityAssetList,
            placeholder: '请选择资产',
            params: params.value,
            resultField: 'data',
            labelField: 'name',
            valueField: 'id.id',
            immediate: true,
            onSearch: useDebounceFn((e) => {
              entityName.value = e;
            }, 300),
            onChange: () => {
              try {
                const { updateSchema } = formActionType;
                updateSchema([
                  {
                    field: 'clientProperties',
                    show: true,
                  },
                  {
                    field: 'sharedProperty',
                    show: true,
                  },
                  {
                    field: 'serverProperties',
                    show: true,
                  },
                  {
                    field: 'timeSeries',
                    show: true,
                  },
                ]);
              } catch (error) {}
            },
          };
        },
      },
    ]);
  }
</script>
